import Controller from './Controller';

export default class RadioController extends Controller {

	constructor( parent, object, property, options, config) {
		if(config == null) config = {} ;
		super( parent, object, property, 'radio' ,'label',config);

		this.$span = document.createElement("span") ;
		this.$span.classList.add("controller") ;
		this.$span.classList.add("radioController") ;

		this.radioName = `gui-radio-${++Controller.nextNameID}`;
		this.$array = [] ;
		this.$spanArray = [] ;
		let index = 0 ;
		for(let key in options){
			let tempId = this.radioName + "-" + index++;

			let itemSpan = document.createElement("span") ;
			itemSpan.classList.add("radioInnerSpan") ;

			let temp = document.createElement( 'input' );
			temp.setAttribute('type', "radio");
			temp.setAttribute("id",tempId) ;
			temp.setAttribute("name",this.radioName) ;
			temp.setAttribute('value', options[key]);

			let tempLabel = document.createElement( 'label' );
			tempLabel.setAttribute("for",tempId) ;
			tempLabel.classList.add("radioLabel") ;
			tempLabel.innerHTML = key ;

			itemSpan.appendChild( temp );
			itemSpan.appendChild( tempLabel );

			this.$span.appendChild( itemSpan );

			this.$array.push(temp) ;
			this.$spanArray.push(itemSpan) ;

			temp.addEventListener( 'change', (e) => {
				this.setValue(e.target.value);
				this._callOnFinishChange();
			});

		};


		this.$widget.appendChild( this.$span );


		this._appendEndDomHtml(config.endHtml) ;
		// let endHtml = config.endHtml ;
		// if(endHtml != null && endHtml != ""){
		// 	this.$span = document.createElement( 'span' );
		// 	this.$span.classList.add("lilInlineEndSpan") ;
		// 	this.$widget.appendChild( this.$span );
		//
		// 	this.$span.innerHTML = endHtml ;
		// }

		this.$disable = this.$span ;

		this.updateDisplay();
	}

	/**
	 * 分项添加注释
	 * @param data
	 */
	itemTooltip(data){
		if(data == null) return this ;
		for(let i=0; i<this.$array.length; i++){
			let t = this.$array[i] ;
			let tip = data[t.value] ;
			if(tip != null && tip != ""){
				t.setAttribute("title",tip) ;
				if(t.parentElement != null)
					t.parentElement.setAttribute("title",tip) ;
			}
		}
		return this ;
	}

	/**
	 * 分项样式
	 * @param data {"value":"style"}
	 */
	itemSpanStyle(data){
		if(data == null) return this ;
		if(this.$spanArray.length != this.$array.length) return this ;

		for(let i=0; i<this.$spanArray.length; i++){
			let span = this.$spanArray[i] ;
			let t = this.$array[i] ;
			let style = data[t.value] ;
			if(style != null && style != ""){
				span.setAttribute("style",style) ;
			}
		}
		return this ;
	}

	updateDisplay() {
		const value = this.getValue();

		for(let i=0; i<this.$array.length; i++){
			let t = this.$array[i] ;
			if(t.value == value){
				t.checked = true ;
				return this ;
			}
		}

		return this;
	}
}
